
package com.starshineworks.util;

import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import au.com.bytecode.opencsv.CSVReader;

public class FileUploader {

    private static final String TMP_DIR_PATH = Util.isWindows ? "c:\\temp" : "/tmp"; // on client
    private File                tmpDir;
    private static final String DESTINATION_DIR_PATH = Util.userHome + "/tmp"; // on server
    private File                destinationDir;
    HttpServletRequest          request  = null;
    HttpServlet                 servlet  = null;

    public FileUploader(HttpServlet serv, HttpServletRequest req) {
        request = req;
        servlet = serv;
    }
    
    public boolean init() {
        if (request == null || servlet == null) {
            return false;
        }
        tmpDir = new File(TMP_DIR_PATH);
        if (!tmpDir.isDirectory()) {
            if(!tmpDir.mkdirs()) {
                return false;
            }
        }
        String realPath = DESTINATION_DIR_PATH;
        destinationDir = new File(realPath);
        if (!destinationDir.isDirectory()) {
            if (!destinationDir.mkdirs()) {
                return false;
            }
        }        
        return true;
    }

    public File getFileContents() { 
        List<File> list = getFilesContents(false);
        if (list != null) {
            if (!list.isEmpty()) {
                return list.get(0);
            }
        }
        return null;
    }

    public List<File> getFilesContents(boolean multiple) { 
        // Is it one-team form?
        boolean multiPartForm = request.getContentType() != null && 
                                request.getContentType().toLowerCase().indexOf("multipart/form-data") > -1;
        if (!multiPartForm) {
            return null;
        }
        // Is it import from xls ?
        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
        fileItemFactory.setSizeThreshold(1 * 1024 * 1024); //1 MB
        fileItemFactory.setRepository(tmpDir);
        ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
        List files = new ArrayList<File>();
        try {
            List items = uploadHandler.parseRequest(request);
            Iterator itr = items.iterator();
            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();
                if (!item.isFormField()) {
                    File file = new File(destinationDir, item.getName());
                    item.write(file);
                    files.add(file);
                    if (!multiple) {
                        return files;
                    }
                }
            }
        } catch (Exception e) {
            Util.handleException(e);
        }        
        return files;
    }
    
    public boolean importFromServlet(String typeName) {
        if (!init()) {
            return false;
        }
        File file = getFileContents();
        return importFromFile(file, typeName);
    }

    public static boolean importFromFile(String fileName, String typeName) 
    {
        File file = new File(fileName);
        return importFromFile(file, typeName);
    }
    
    public static boolean importFromFile(File file, String typeName) 
    {
        try {
            Class type = Class.forName("com.starshineworks.entities." + typeName);
            CSVReader reader = new CSVReader(new FileReader(file));
            List<String[]> matrix = reader.readAll();
            if (matrix.size() < 2) {
                return false;
            }
            DataMatrixElab dme = new DataMatrixElab(matrix);
            dme.updateDb(type);
        } catch (Exception e) {
            Util.handleException(e);
            return false;
        }
        return true;
    }
}
    